// Import the framework and instantiate it
const fastify = require("fastify")({ logger: true });
const mongoose = require("mongoose");
const config = require("../config/config"); // Import config
// 引入初始化目录工具
const { initHandleDeployDir } = require("./utils/makedir");
// Enable CORS
fastify.register(require("@fastify/cors"), {
  origin: true,
  methods: ["GET", "PUT", "POST", "DELETE", "OPTIONS"],
  allowedHeaders: ["Content-Type", "Authorization", "Content-Range"],
});
// Register static file serving
fastify.register(require("@fastify/static"), {
  root: require("path").join(__dirname, "../front"),
  prefix: "/", // 可选：设置访问静态资源的URL前缀
});
// Register formbody support for parsing form data
fastify.register(require("@fastify/multipart"), {
  limits: {
    fileSize: 200 * 1024 * 1024, // 限制文件大小为100MB
  },
});

// Register WebSocket support
fastify.register(require("@fastify/websocket"));

// Connect to MongoDB
mongoose
  .connect(config.mongodbUri)
  .then(() => fastify.log.info("MongoDB connected successfully"))
  .catch((err) => {
    fastify.log.error("MongoDB connection error:", err);
    process.exit(1);
  });

// Declare a route
fastify.get("/", async (request, reply) => {
  return reply.sendFile('index.html');
});

// Register system routes
fastify.register(require("./routes/systemRoutes"));

// Register WebSocket routes
fastify.register(require("./routes/socketClient"));

// Register upload routes
fastify.register(require("./routes/uploadRoutes"), { prefix: "/api" });
// Register UE project routes
fastify.register(require("./routes/ueProjectRoutes"), { prefix: "/api" });
// Register UE instance routes
fastify.register(require("./routes/ueInstanceRoutes"), { prefix: "/api" });
// Register UE SDK routes
fastify.register(require("./routes/ueSdkRoutes"), { prefix: "/api" });
// Run the server!
const start = async () => {
  try {
    await fastify.listen({ port: config.port }); // Use port from config
    // Log message is handled by Fastify's default logger
    // 启动后初始化文件夹
    initHandleDeployDir();
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();
